package org.richin.web.struts.util;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.tiles.DefinitionsFactoryException;
import org.apache.struts.tiles.TilesUtil;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;

public class StrutsUtil {
	private final static Log log = LogFactory.getLog(StrutsUtil.class);
	public static final String SUCCESS = "success";
	public static final String DIRECTLY_MESSAGE_KEY = "message";
	public static final String ERROR = "error";
	public static final String INPUT = "input";
	public static final String LOGIN = "login";
	public static final String LIST = "list";
	public static final String EDIT = "edit";
	public static final String VIEW = "view";

	public static void setAlertMessage(HttpServletRequest request, String message) {
		request.setAttribute("msg", "<script>alert('" + message + "');</script>");
	}

	public enum Scope {
		FORM, REQUEST, SESSION, APPLICATION
	}

	/**
	* 直接输出纯Json.
	*/
	public static void printJson(HttpServletResponse response, String text) {
		doPrint(response, text, "text/x-json;charset=UTF-8");
	}

	/**
	* 直接输出纯XML.
	*/
	public static void printXML(HttpServletResponse response, String text) {
		doPrint(response, text, "text/xml;charset=UTF-8");
	}

	/**
	* 直接输出纯HTML.
	*/
	public static void printHtml(HttpServletResponse response, String text) {
		doPrint(response, text, "text/html;charset=UTF-8");
	}

	/**
	* 直接输出纯字符串.
	*/
	public static void printText(HttpServletResponse response, String text) {
		doPrint(response, text, "text/plain;charset=UTF-8");
	}

	public static void setResponseNoCache(HttpServletResponse response) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
	}

	private static void doPrint(HttpServletResponse response, String text, String contentType) {
		try {
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * Returns the form action converted into an action mapping path.  The
	 * value of the <code>action</code> property is manipulated as follows in
	 * computing the name of the requested mapping:
	 * <ul>
	 * <li>Any filename extension is removed (in the theory that extension
	 * mapping is being used to select the controller servlet).</li>
	 * <li>If the resulting value does not start with a slash, then a
	 * slash is prepended.</li>
	 * </ul>
	 *
	 * @param action action URI
	 * @return mapping name
	 */
	protected static String getActionMappingName(String action) {

		String value = action;
		int question = action.indexOf("?");
		if (question >= 0) {
			value = value.substring(0, question);
		}

		int slash = value.lastIndexOf("/");
		int period = value.lastIndexOf(".");
		if ((period >= 0) && (period > slash)) {
			value = value.substring(0, period);
		}

		return value.startsWith("/") ? value : ("/" + value);
	}

	/**
	 * 用javascript弹出提示信息
	 *
	 * @param msg
	 *            显示的信息
	 * @return String
	 * @throws IOException
	 * @author hezhenbo
	 */
	protected String jsAlert(HttpServletResponse response, String msg) {
		try {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print("<script language='javascript'>alert('" + msg + "');</script>");
			out.close();
			return null;
		} catch (Exception e) {
			log.error("jsAlert(" + msg + ") error", e);
			return null;
		}
	}

	/**
	 * 直接输出二进制数组.
	 *
	 * 通常用于直接输出图片或者附件等
	 * @param mimetype
	 *            要输出的内容的MimeType
	 * @param content
	 *            要输出的内容
	 */
	public void renderBinary(HttpServletResponse response, String mimetype, byte[] content) {
		try {
			response.setContentType(mimetype);
			ServletOutputStream out = response.getOutputStream();
			BufferedOutputStream bo = new BufferedOutputStream(out, 1024);
			bo.write(content);
			bo.flush();
			bo.close();
			out.close();
		} catch (IOException e) {
			log.error(e);
		}
	}

	/**
	 * 直接输出二进制数组.
	 *
	 * 通常用于直接输出图片或者附件等
	 * @param mimetype
	 *            要输出的内容的MimeType
	 * @param source
	 *            包含要输出的内容的输入流
	 */
	public void renderBinary(HttpServletResponse response, String mimetype, InputStream source) {
		try {

			response.setContentType(mimetype);
			ServletOutputStream out = response.getOutputStream();
			byte[] buffer = new byte[1024];
			while (source.read(buffer) > 0) {
				out.write(buffer);
				out.flush();
			}
			out.close();
			source.close();
		} catch (IOException e) {
			log.error(e);
		}
	}
}
